import axios from 'axios'
import store from '@/store'
import { getSessionItem } from "@/utils/sessionStorage";
axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: "http://10.62.11.69:10043/gatway",
  // 超时
  timeout: 5000,
});

// request拦截器
service.interceptors.request.use(config => {
  config.headers["token"] = store.state.homeStatus.E_token || getSessionItem();
  
  return config;
}, error => {
   
    Promise.reject(error)
})

// 响应拦截器
service.interceptors.response.use(res => {
  
      return res.data
    
  },
  error => {
  
    // let { message } = error;
    // if (message == "Network Error") {
    //   message = "当前网络不稳定，请稍后再试";
    // }
    // else if (message.includes("timeout")) {
    //   message = "当前网络不稳定，请稍后再试";
    // }
    // else if (message.includes("Request failed with status code")) {
    //   message = "当前网络不稳定，请稍后再试";
    // }
    // Message({
    //   message: message,
    //   type: 'error',
    //   duration: 5 * 1000
    // })
    return Promise.reject(error)
  }
)

// 通用下载方法
export function download(url, params, filename) {
  downloadLoadingInstance = Loading.service({ text: "正在下载数据，请稍候", spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.7)", })
  return service.post(url, params, {
    transformRequest: [(params) => { return tansParams(params) }],
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    responseType: 'blob'
  }).then(async (data) => {
    const isLogin = await blobValidate(data);
    if (isLogin) {
      const blob = new Blob([data])
      saveAs(blob, filename)
    } else {
      const resText = await data.text();
      const rspObj = JSON.parse(resText);
      const errMsg = rspObj.msg
      Message.error(errMsg);
    }
    downloadLoadingInstance.close();
  }).catch((r) => {
    console.error(r)
    Message.error('下载文件出现错误')
    downloadLoadingInstance.close();
  })
}

export default service
